package com.ojoin.ojoin.eb_spider.service.catchdata;

import java.io.File;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.ojoin.trade.common.utils.DownloadUtils;
import com.ojoin.trade.common.utils.WaitUtil;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ojoin.ojoin.eb_spider.dao.PhysicalEaminationMapper;
import com.ojoin.ojoin.eb_spider.domain.AssistCatchData;
import com.ojoin.ojoin.eb_spider.domain.BankCardCheck;
import com.ojoin.ojoin.eb_spider.model.PhysicalEamination;
import com.ojoin.ojoin.eb_spider.service.WebDriverService;
import com.ojoin.ojoin.eb_spider.service.impl.SLDataCatchBaseServiceImpl;
import com.ojoin.ojoin.eb_spider.unZip.ZipDecompressingUtils;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.TimeUtils;

/**
 *
 *
 *
 */

@Service
public class MeiNianDataCatchServiceImpl2 extends SLDataCatchBaseServiceImpl {

    /**
     * 线程内共享Connection，ThreadLocal通常是全局的，支持泛型
     */
    private static ThreadLocal<Set<String>> names = new ThreadLocal<Set<String>>();

    @Autowired
    private PhysicalEaminationMapper physicalEaminationMapper;

    private static Logger log = LoggerFactory.getLogger(MeiNianDataCatchServiceImpl2.class);

    @Override
    public boolean isLoginSuccess() throws Exception {
        boolean loginflag = false;

        String username = this.getAssistCatchData().getStartMess().getPlatformUser().getUsername();
        String password = this.getAssistCatchData().getStartMess().getPlatformUser().getPassword();

        String loginUrl = this.getAssistCatchData().getStartMess().getPlatformInfo().getLoginUrl();

        loginflag = LoginByUserInfo(loginUrl, username, password);

        return loginflag;
    }

    @Override
    public boolean LoginByUserInfo(String baseUrl, String username, String password) throws Exception {
        // 开始登陆
        //try {
        this.getWebDriver().get("http://meinian.cn/Research.aspx ");

        this.getWebDriver().click(WebDriverService.CSS, "#ctl00_ContentPlaceHolder1_uStyle > option:nth-child(2)");

        this.getWebDriver().sendKeys("id", "ctl00_ContentPlaceHolder1_uCard", username);
        this.getWebDriver().sendKeys("id", "ctl00_ContentPlaceHolder1_uPass", password);

        boolean flag = this.getWebDriver().IsDisplayed("id", "ctl00_ContentPlaceHolder1_Image2");
        if (flag) {
            WebElement verifyE = this.getWebDriver().findElement(WebDriverService.ID,
                    "ctl00_ContentPlaceHolder1_Image2");
            String code = this.getWebDriver().getVerifyCodeByDMV3(verifyE);

            this.getWebDriver().sendKeys(WebDriverService.ID, "ctl00_ContentPlaceHolder1_txtVerifyCode",
                    code.toLowerCase());
        }

        this.getWebDriver().click("id", "ctl00_ContentPlaceHolder1_button1");

		/*} catch (Exception e) {
                        log.error(" ", e);

		}*/

        return this.getWebDriver().getDriver().getCurrentUrl().startsWith("http://meinian.cn/ResearchEntResult.aspx");
    }

    public void initDownloadDir() {

        String mapping_download_dir = getDownLoadFile();

        this.getAssistCatchData().setDownloadDir(mapping_download_dir);

        LogUtils.info(log, "下载路径download.dir 映射目录-->" + mapping_download_dir);
    }

    /**
     * 当日下载路径
     */

    public String getDownLoadFile() {
        String mapping_download_dir = null;

        mapping_download_dir = System.getProperties().getProperty("user.home") + File.separator + "Downloads"
                + File.separator + this.getAssistCatchData().getStartMess().getPlatformUser().getPlatformName()
                + File.separator + TimeUtils.getCurDate()
                + File.separator + this.getAssistCatchData().getStartMess().getPlatformUser().getUsername()

        ;

        return mapping_download_dir;

    }

    /**
     * 历史遗留，兼容以前数据，已经存在数据不进行下载
     * @return
     */
    public String getInitDownLoadFile() {

        String mapping_download_dir = System.getProperties().getProperty("user.home") + File.separator + "Downloads"
                + File.separator + this.getAssistCatchData().getStartMess().getPlatformUser().getPlatformName()
                + File.separator + this.getAssistCatchData().getStartMess().getPlatformUser().getUsername();

        return mapping_download_dir;

    }


    @Override
    public void catchData(AssistCatchData assistCatchData) throws Exception {

        try {
            super.init(assistCatchData);
            init();

            prepareCatchData();

            boolean flag = isLoginSuccess();

            if (flag) {

                doit();

            }

            File downloadFileDir = new File(getDownLoadFile());

            boolean dflag = DownloadUtils.waitFileDownloadOverByTmp(downloadFileDir,
                    "download$");
            log.info("dflag:--------->" + dflag);

            init();
        } catch (Exception e) {
            LogUtils.error(log, e);
            throw e;

        } finally {
            // 需要确定文件已经下载完毕


            closeCatchData(false, false);
        }
    }

    @Override
    public String catchSupplierName() throws BusinessException {
        initCompanyInfomation();
        String name = "";

        return name;
    }

    // 减压
    public void unzip(String dowmload) {
        ZipDecompressingUtils.unZip(dowmload, dowmload, Charset.forName("GBK"));
    }

    /**
     * 已下载pdf更新状态
     */


    public void init() {
        Set<String> nas = new HashSet<>();

        names.set(nas);

        String dowmload = getDownLoadFile();

        String d2 = getInitDownLoadFile();

        unzip(dowmload);


        updateStatus(dowmload, nas);
        updateStatus(d2, nas);


        // http://b2bi.gome.com.cn/gmol/sellVatInvQry/detail.hlt?invid=2041525

    }

    public void updateStatus(String dowmload, Set<String> nas) {
        File file = new File(dowmload);
        PhysicalEamination pe = new PhysicalEamination();
        pe.setStatus(2);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File fi : files) {
                if (fi.isFile()) {
                    String name = fi.getName();
                    if (name.contains(".pdf")) {
                        String[] names = name.split(".pdf");
                        if (names.length > 0) {
                            String na = names[0].substring(0,names[0].indexOf("_"));
                            pe.setId(na);
                            nas.add(names[0]);
                            physicalEaminationMapper.updateByPrimaryKeySelective(pe);
                        }
                    }

                }
            }
        }
    }

    public void initCompanyInfomation() {

        // http://b2bi.gome.com.cn/gmol/sellVatInvQry/detail.hlt?invid=2041525

    }

    public void search() {
        // try {

        this.getWebDriver().click(WebDriverService.xpath, "//*[@id=\"drpArea\"]");

        List<WebElement> options = this.getWebDriver().findElements(WebDriverService.CSS, "#drpArea option");

        for (WebElement option : options) {
            if ("001".equals(option.getAttribute("value"))) {
                option.click();
            }
        }

        //this.getWebDriver().click(WebDriverService.xpath, "//*[@id=\"drpArea\"]/option[32]");

        this.getWebDriver().click(WebDriverService.xpath, "//*[@id=\"Button1\"]");

        // } catch (Exception e) {

        // LogUtils.error(log, e);
        // throw e;
        // }
    }

    public void deal() {
        String username = this.getAssistCatchData().getStartMess().getPlatformUser().getUsername();

        Map<String, PhysicalEamination> map = getPhysicalEaminationMap(username);

        deallPage(map, username);

    }

    public void deallPage(Map<String, PhysicalEamination> map, String username) {
        //try {
        int pa = 0;
        List<WebElement> tds = this.getWebDriver().findElements(WebDriverService.CSS,
                "#GridView1 > tbody > tr:nth-child(18) > td > table > tbody > tr > td");

        if (null != tds && tds.size() > 0) {
            for (int i = 0; i < tds.size(); i++) {
                WebElement td = tds.get(i);

                if (i == tds.size() - 1) {
                    // 下一个十个页面，需要下载
                    if ("...".equals(td.getText())) {
                        log.info("下一个十页");
                        this.getWebDriver().click(td, WebDriverService.CSS, "a");
                        deallPage(map, username);
                        break;
                    } else {

                        log.info("最后一页:" + td.getText());
                        if (this.getWebDriver().IsExist(td, WebDriverService.CSS, "a")) {
                            this.getWebDriver().click(td, WebDriverService.CSS, "a");
                            deallPage(map, username);
                            break;

                        } else {
                            log.info("当前页数：" + td.getText());
                            dealTable(map, username);
                        }

                    }

                    // this.getWebDriver().click(WebDriverService.xpath,
                    // "//*[@id=\"Div4\"]/table/tbody/tr[1]/td/input[2]");
                    // deallPage(map,username);
                } else {
                    if (!"...".equals(td.getText())) {
                        int pag = Integer.valueOf(td.getText());
                        if (this.getWebDriver().IsExist(td, WebDriverService.CSS, "a")) {
                            if (pa != 0 && pa == pag - 1) {
                                // log.info("获取下一页：" + td.getText());
                                this.getWebDriver().click(td, WebDriverService.CSS, "a");
                                deallPage(map, username);
                                break;
                            }
                            // dealTable();

                        } else {
                            log.info("当前页数：" + td.getText());
                            dealTable(map, username);
                            pa = pag;
                        }
                    }

                }

            }

        } else {
            dealTable(map, username);
        }

        //} catch (Exception e) {

        //	LogUtils.error(log, e);
        //	throw e;
        //}
    }

    // *[@id="GridView1"]/tbody/tr[18]/td/table

    /**
     * 处理搜索的数据
     */
    public void dealTable(Map<String, PhysicalEamination> map, String username) {
        //try {
        // 登录名 这里用作公司id

        List<PhysicalEamination> set = new ArrayList<>();
        Set<String> nas = names.get();

        List<WebElement> trs = this.getWebDriver().findElements(WebDriverService.CSS, "#GridView1 tbody tr");
        boolean flag = false;

        for (WebElement tr : trs) {
            if (this.getWebDriver().IsExist(tr, WebDriverService.CSS, "td:nth-child(1) > input")) {

                WebElement input = this.getWebDriver().findElement(tr, WebDriverService.CSS,
                        "td:nth-child(1) > input");
                String id = input.getAttribute("value");

                if (null != map.get(id)) {
                    if (map.get(id).getStatus() == 1) {
                        if (!nas.contains(id)) {
                            input.click();
                            flag = true;
                        }
                    }

                } else {
                    String name = this.getWebDriver().findElement(tr, WebDriverService.CSS, " td:nth-child(2)")
                            .getText();
                    String numId = this.getWebDriver().findElement(tr, WebDriverService.CSS, " td:nth-child(3)")
                            .getText();
                    String sex = this.getWebDriver().findElement(tr, WebDriverService.CSS, " td:nth-child(4)")
                            .getText();
                    String birthDay = this.getWebDriver().findElement(tr, WebDriverService.CSS, " td:nth-child(5)")
                            .getText();

                    String carded = this.getWebDriver().findElement(tr, WebDriverService.CSS, " td:nth-child(6)")
                            .getText();

                    String appointmentDate = this.getWebDriver()
                            .findElement(tr, WebDriverService.CSS, " td:nth-child(7)").getText();

                    PhysicalEamination pe = new PhysicalEamination();
                    pe.setAppointmentdate(appointmentDate);
                    pe.setBirthday(birthDay);
                    pe.setCarded(carded);
                    pe.setCompanyId(username);
                    pe.setNumid(numId);
                    pe.setSex(sex);
                    pe.setStatus(1);
                    pe.setUsername(name);
                    pe.setId(id);

                    if (null == nas || !nas.contains(id)) {
                        input.click();
                        flag = true;
                    }

                    set.add(pe);
                }
            }
        }

        if (null != set && set.size() > 0) {
            physicalEaminationMapper.insertBatch(set);

        }

        // 下载报告

        if (flag) {
            this.getWebDriver().click(WebDriverService.xpath, "//*[@id=\"Div4\"]/table/tbody/tr[1]/td/input[2]",
                    300);

        }

        //} catch (Exception e) {

        //	LogUtils.error(log, e);
        //	throw e;
        //}
    }

    public Map<String, PhysicalEamination> getPhysicalEaminationMap(String companyId) {
        Map<String, PhysicalEamination> map = new HashMap<String, PhysicalEamination>();
        List<PhysicalEamination> li = physicalEaminationMapper.selectByCompanyId(companyId);

        if (null != li && li.size() > 0) {
            for (PhysicalEamination pe : li) {
                map.put(pe.getId(), pe);
            }
        }

        return map;

    }

    public boolean doit() {
        search();
        deal();

        return true;
    }

    @Override
    public boolean getUnpayAccountData() throws BusinessException {
        return true;

    }

    @Override
    public boolean getInstoreOrderData() throws BusinessException {

        return true;
    }

    @Override
    public boolean getOutstoreOrderData() throws BusinessException {
        // 送货记录
        // 对账单
        return true;
    }

    @Override
    public boolean getPayAccountData() throws BusinessException {
        return true;
    }

    @Override
    public BankCardCheck catchSupplierAccount() throws BusinessException {
        // TODO Auto-generated method stub
        return null;
    }

}
